package com.sicnu.cheer.leaugebar.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.os.Build;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.CardView;
import android.transition.Transition;
import android.transition.TransitionInflater;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.animation.AccelerateInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.sicnu.cheer.generalmodule.activity.BaseActivity;
import com.sicnu.cheer.generalmodule.bean.LeagueBean;
import com.sicnu.cheer.generalmodule.util.ScreenUtils;
import com.sicnu.cheer.generalmodule.util.StringUtils;
import com.sicnu.cheer.generalmodule.util.UIHelper;
import com.sicnu.cheer.leaugebar.R;
import com.sicnu.cheer.generalmodule.bean.MyUser;
import com.sicnu.cheer.leaugebar.utils.CountDownTimerUtils;
import com.sicnu.cheer.generalmodule.util.ValidateUtil;

import butterknife.InjectView;
import butterknife.OnClick;
import cn.bmob.v3.BmobSMS;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.RequestSMSCodeListener;
import cn.bmob.v3.listener.ResetPasswordByCodeListener;
import cn.bmob.v3.listener.SaveListener;

/**
 * Created by cheer on 2016/10/23.
 * 注册或者重置密码页面
 */
public class RegisterOrResetActivity extends BaseActivity {
    private static final String COUNTRY_CODE="86";//默认中国区号
    private final String TAG="RegisterOrResetActivity";
    @InjectView(R.id.fab)
    FloatingActionButton fab;
    @InjectView(R.id.cv_add)
    CardView cvAdd;
    @InjectView(R.id.send_verify_btn)
    Button sendVerify;
    @InjectView(R.id.register_reset_tv)
    TextView registerOrReset;
    @InjectView(R.id.et_phone)
    EditText phoneET;
    @InjectView(R.id.et_verify_code)
    EditText verifyCodeET;
    @InjectView(R.id.et_password)
    EditText passwordET;
    @InjectView(R.id.et_repeatpassword)
    EditText repeatPasswordET;

    private boolean isRegister;
    private String phone;
    private String code;
    private String password;

    @Override
    protected void initData() {
        super.initData();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ShowEnterAnimation();
        }
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                animateRevealClose();
            }
        });

        isRegister = getIntent().getBooleanExtra("isRegister",false);
    }

    @Override
    protected void afterViews() {
        super.afterViews();
        registerOrReset.setText(getResources().getString(isRegister?R.string.register:R.string.password_reset));
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_register_or_reset;
    }

    private void ShowEnterAnimation() {
        Transition transition = TransitionInflater.from(this).inflateTransition(R.transition.fabtransition);
        getWindow().setSharedElementEnterTransition(transition);

        transition.addListener(new Transition.TransitionListener() {
            @Override
            public void onTransitionStart(Transition transition) {
                cvAdd.setVisibility(View.GONE);
            }

            @Override
            public void onTransitionEnd(Transition transition) {
                transition.removeListener(this);
                animateRevealShow();
            }

            @Override
            public void onTransitionCancel(Transition transition) {

            }

            @Override
            public void onTransitionPause(Transition transition) {

            }

            @Override
            public void onTransitionResume(Transition transition) {

            }


        });
    }

    public void animateRevealShow() {
        Animator mAnimator = ViewAnimationUtils.createCircularReveal(cvAdd, cvAdd.getWidth() / 2, 0, fab.getWidth() / 2, cvAdd.getHeight());
        mAnimator.setDuration(500);
        mAnimator.setInterpolator(new AccelerateInterpolator());
        mAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
            }

            @Override
            public void onAnimationStart(Animator animation) {
                cvAdd.setVisibility(View.VISIBLE);
                super.onAnimationStart(animation);
            }
        });
        mAnimator.start();
    }

    public void animateRevealClose() {
        Animator mAnimator = ViewAnimationUtils.createCircularReveal(cvAdd, cvAdd.getWidth() / 2, 0, cvAdd.getHeight(), fab.getWidth() / 2);
        mAnimator.setDuration(500);
        mAnimator.setInterpolator(new AccelerateInterpolator());
        mAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                cvAdd.setVisibility(View.INVISIBLE);
                super.onAnimationEnd(animation);
                fab.setImageResource(R.mipmap.plus);
                RegisterOrResetActivity.super.onBackPressed();
            }

            @Override
            public void onAnimationStart(Animator animation) {
                super.onAnimationStart(animation);
            }
        });
        mAnimator.start();
    }

    @OnClick({R.id.send_verify_btn, R.id.bt_go})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.send_verify_btn:
                sendVerificationCode();
                break;
            case R.id.bt_go:
                //手动隐藏键盘
                ScreenUtils.hideKeyboard(mThis);
                //检测输入合法性
                if (checkValid()) {
                    performRegisterOrReset();
                }
                break;
            default:
                break;
        }
    }

    private void sendVerificationCode() {
        //1、验证手机号合法性
        String phone = phoneET.getText().toString().trim().replaceAll("\\s*", "");
        if (ValidateUtil.isMobile(phone)){
            //2、发送验证码到手机
            BmobSMS.requestSMSCode(mThis, phone, COUNTRY_CODE,new RequestSMSCodeListener() {
                @Override
                public void done(Integer smsId,BmobException ex) {
                    if(ex==null){
                        //验证码发送成功
                    }else {
                        UIHelper.ToastMessage(mThis,"验证码发送失败:"+ex.getLocalizedMessage());
                    }
                }
            });
            //3、发送验证码之后开始倒计时
            CountDownTimerUtils mCountDownTimerUtils = new CountDownTimerUtils(sendVerify, 60000, 1000);
            mCountDownTimerUtils.start();
        }else {
            UIHelper.ToastMessage(mThis,"清输入正确的手机号！");
        }
    }

    //进行注册操作
    private void performRegisterOrReset() {
        if (isRegister) {
            MyUser user = new MyUser();
            user.setNick("--");
            user.setSex("男");
            user.setMobilePhoneNumber(phone);//设置手机号码（必填）
            user.setUsername(phone);//设置用户名，如果没有传用户名，则默认为手机号码
            user.setPassword(password);//设置用户密码
            user.setHeadPic("");
            user.setInit(false);
            user.setManager(false);
            LeagueBean league=new LeagueBean();
            league.setObjectId("f0UnJJJa");//用户注册时设置默认社团（川师学生会）
            user.setLeague(league);
            user.signOrLogin(mThis, code, new SaveListener() {
                @Override
                public void onSuccess() {
                    UIHelper.ToastMessage(mThis, "用户注册成功");
                    finish();
                }

                @Override
                public void onFailure(int code, String msg) {
                    UIHelper.ToastMessage(mThis,"注册失败："+msg);
                }
            });

        }else{
            BmobUser.resetPasswordBySMSCode(mThis, code,password, new ResetPasswordByCodeListener() {
                @Override
                public void done(BmobException ex) {
                    if(ex==null){
                        UIHelper.ToastMessage(mThis, "重置密码成功");
                        finish();
                    }else{
                        UIHelper.ToastMessage(mThis,"重置失败："+ex.getLocalizedMessage());
                    }
                }
            });
        }
    }
    private boolean checkValid() {
        //1、手机号和验证码验证
        phone = phoneET.getText().toString().trim().replaceAll("\\s*", "");
        code = verifyCodeET.getText().toString().trim();
        if (StringUtils.isEmpty(phone)) {
            UIHelper.ToastMessage(mThis,"请输入手机号！");
            return false;
        }
        if (StringUtils.isEmpty(code)){
            UIHelper.ToastMessage(mThis,"请输入验证码！");
            return false;
        }
        //2、密码和确认密码验证
        password = passwordET.getText().toString();
        String repeatPassword=repeatPasswordET.getText().toString();
        if (StringUtils.isEmpty(password)){
            UIHelper.ToastMessage(mThis,"请输入密码！");
            return false;
        }
        if (StringUtils.isEmpty(repeatPassword)){
            UIHelper.ToastMessage(mThis,"请输入确认密码！");
            return false;
        }
        if (!password.equals(repeatPassword)){
            UIHelper.ToastMessage(mThis,"密码和确认密码不一致，请重置");
            passwordET.setText("");
            repeatPasswordET.setText("");
            return false;
        }
        return true;
    }


    @Override
    public void onBackPressed() {
        animateRevealClose();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
